#include <iostream>
#include <vector>

using namespace std;

int lastStoneWeight(vector<int>& stones) {
        vector<int> new_stones;
        int biggest, bigger, last_stone_weight, biggest_index, bigger_index, 
            last_biggest_index, last_bigger_index;
        while(stones.size()>1){
            for(int i = 0; i<  stones.size(); ++i) cout << stones[i] << " ";
            cout << "\n";
            if(stones[0] > stones[1]){
                biggest = stones[0];
                bigger  = stones[1];
                last_biggest_index = biggest_index = 0;
                last_bigger_index = bigger_index = 1;
            }else{
                biggest = stones[1];
                bigger  = stones[0];
                last_biggest_index = biggest_index = 1;
                last_bigger_index = bigger_index = 0;
            }

            cout << "Beginning biggest: " << biggest << ", bigger: " << bigger << "\n";
        
            if(stones.size() == 2){
                cout << "only 2 stones\n";
                if ((biggest - bigger) == 0){
                    return 0;
                }else{
                    return biggest - bigger;
                }
            }else{
                for(auto i = 2; i < stones.size(); ++i){
                    if(stones[i] > biggest){
                        bigger = biggest;
                        bigger_index = last_biggest_index;
                        biggest = stones[i];
                        last_biggest_index = biggest_index = i;
                         
                    }else if(stones[i] > bigger) {
                        bigger = stones[i];
                        bigger_index = i;
                    }
                    
                }

                cout << "Then biggest: "  << biggest << " " << bigger << "\n"
                     << "biggest index: " << biggest_index << " " <<  bigger_index << "\n";

                if(biggest_index > bigger_index){
                    stones.erase(stones.begin() + biggest_index);
                    stones.erase(stones.begin() + bigger_index);
                }else{
                    stones.erase(stones.begin() + bigger_index);
                    stones.erase(stones.begin() + biggest_index);
                }
                
                cout << "After deleting: ";
                for(int i = 0; i<  stones.size(); ++i) cout << stones[i] << " ";
                cout << "\n\n";

                if(biggest != bigger)
                    stones.push_back(biggest - bigger);

            }
            
        }
    if(stones.size() == 1) return stones[0];
    else return 0;
        
}

int main() {
    vector<int> example  {5,1,8,10,7};
    int last_weight = lastStoneWeight(example);
    cout << last_weight << "\n";
    return 0;
}